<?php

namespace common\models\service;

use common\helpers\commonApi;
use common\helpers\TransformApi;
use common\models\Campus;
use common\models\GoodsSpec;
use common\models\GoodsStock;
use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "{{%goods_stock}}".
 *
 * @property int $id
 * @property int|null $good_id 商品id
 * @property int|null $spec_id 规格id
 * @property int|null $campus_id 校区id
 * @property int|null $stock 库存
 * @property int|null $sales 销量
 * @property string|null $create_time 创建时间
 * @property string|null $create_user 创建人
 * @property string|null $update_time 修改时间
 * @property string|null $update_user 修改人
 * @property string|null $mark 标记
 */
class GoodsStockService extends GoodsStock
{

    /**
     * 获取规格库存
     * @param $good_id
     * @param $campus_id
     * @return array
     */
    public static function getSpec($good_id,$campus_id)
    {
         $spec = GoodsSpec::find()->where(['good_id'=>$good_id])->select(['name','id'])->asArray()->all();
         $spec_id = array_column($spec,'id');
         $stock = GoodsStock::find()
             ->select(['gs.stock','c.name','c.id as campus_id','gs.id','gs.spec_id'])
             ->alias('gs')
             ->leftJoin(Campus::tableName().' as c','c.id=gs.campus_id')
             ->where(['gs.good_id'=>$good_id])
             ->andWhere(['gs.spec_id'=>$spec_id])
             ->andFilterWhere(['gs.campus_id'=>$campus_id])
             ->asArray()->all();
         $campus = Campus::find()
             ->andFilterWhere(['id'=>$campus_id,'status'=>1,'delete'=>0])
             ->asArray()->all();
         $specAll = [];
         foreach ($spec as $item){
             $specAll[$item['id']] = ['name'=>$item['name'],'data'=>[]];
             $exitcampus = [];
             foreach ($stock as $st){
                 if ($st['spec_id']==$item['id']){
                     $specAll[$item['id']]['data'][] = [
                         'id'=>$st['id'],
                         'name'=>$st['name'],
                         'stock'=>$st['stock'],
                         'spec_id'=>$item['id'],
                         'campus_id'=>$st['campus_id'],
                         'good_id'=>$good_id,
                     ];
                     $exitcampus[] = $st['campus_id'];
                 }
             }
             foreach ($campus as $cam){
                 if (!in_array($cam['id'],$exitcampus)){
                     $specAll[$item['id']]['data'][] = [
                         'id'=>'',
                         'good_id'=>$good_id,
                         'name'=>$cam['name'],
                         'stock'=>'',
                         'spec_id'=>$item['id'],
                         'campus_id'=>$cam['id'],
                     ];
                 }
             }
         }
         return array_values($specAll);
    }

    /**
     * 设置
     * @param $data
     * @return array|mixed
     */
    public static function setSpec($data)
    {
        $update = [];
        $updateId = [];
        $insert = [];
        $date = date('Y-m-d H:i:s');
        $create_user = Yii::$app->user->identity->realname;
        foreach ($data as $datum){
            $datum['stock'] = $datum['stock']??0;
            if ($datum['stock']<0){
                return commonApi::message('规格必须大于或等于0',false);
            }
            if (!empty($datum['id'])){
                $updateId[] = $datum['id'];
                $update[] = ['stock'=>$datum['stock']];
            }else{
                $insert[] = [
                    'good_id'=>$datum['good_id'],
                    'spec_id'=>$datum['spec_id'],
                    'campus_id'=>$datum['campus_id'],
                    'stock'=>$datum['stock'],
                    'create_time'=>$date,
                    'create_user'=>$create_user,
                    'update_time'=>$date,
                    'update_user'=>$create_user,
                    'mark'=>$datum['campus_id'].'_'.$datum['good_id'].'_'.$datum['spec_id'],
                ];
            }
        }
        if (!$update&&!$insert){
            return commonApi::message('暂无可设置的',false);
        }
        TransformApi::tx(function ()use ($update,$updateId,$insert){
            $updateRes = true;
            $insertRes = true;
            if ($update){
                $sql = TransformApi::batchUpdate(GoodsStock::getTableSchema()->name,$update,$updateId);
                $updateRes = Yii::$app->db->createCommand($sql)->execute();
            }
            if ($insert){
                $key = array_keys($insert[0]);
                $insertRes = (new GoodsStock())->insertAll($key,$insert);
            }
            if ($updateRes!==false&&$insertRes){
                return commonApi::message('设置成功');
            }
            throw new Exception('设置失败');
        },$result);
        return $result;
    }
}
